package Thread_study.thread_synchronized_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId;
    private double money;
    // 锁对象唯一 final修饰后锁对象就是唯一不可替换的,非常专业
    private final Lock lock = new ReentrantLock();

    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    /**
     *  小明 小红
     * @param money
     */
    public void drawMoney(double money) {
        // 0.先获取是谁来取钱
        String name = Thread.currentThread().getName();
        // 1.判断账户是否够钱
        lock.lock(); // 上锁
        try {
            if (this.money >= money) {
                // 2.取钱
                System.out.println(name + "来取钱成功,吐出" + money);
                // 3.更新余额
                this.money -= money;
                System.out.println(name + "取钱后:" + this.money);
            } else {
                // 4.余额不足
                System.out.println(name + "来取钱,余额不足");
            }
        } finally { // 防止代码出现异常导致锁解不开
            lock.unlock(); // 解锁
        }
    }
}
